<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Buypo extends Auth
{
    public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    function getReturnData($data)
    {
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $data[$k]['kgs_sum'] = (string)$data[$k]['kgs_sum'];
                $data[$k]['buy_po_pack'] = getDatas('buy_po_pack',['*'],['po_id'=>$v['id']]);
                        // dump($data[$k]['buy_po_pack']);die;
                $data[$k]['is_container']=0;
                if(!empty($data[$k]['buy_po_pack'])){
                    foreach ($data[$k]['buy_po_pack'] as $k1 => $v1) {
                        if($v1['pro_id']){
                            $proList = model('Buy')->getProAndProchar($v1['pro_id'],$v1['prochar_id'],$this->lang);
                            if(!empty($proList)){
                                $data[$k]['buy_po_pack'][$k1]['pro_name'] = $proList['proList']['content'];
                                $data[$k]['buy_po_pack'][$k1]['brand_name'] = $proList['proList']['brand_name'];
                                $data[$k]['buy_po_pack'][$k1]['img_url'] = $proList['proList']['img_url'];
                                $data[$k]['buy_po_pack'][$k1]['model'] = $proList['prochar']['model'];
                            } 
                        }else{
                            $data[$k]['buy_po_pack'][$k1]['pro_name'] = '';
                        }

                        $data[$k]['buy_po_pack'][$k1]['qty_sum'] = (string)($v1['qty']*$v1['ctn_qty']);
                        $data[$k]['buy_po_pack'][$k1]['kgs_sum'] = (string)($v1['qty']*$v1['ctn_kgs']);
                        $data[$k]['buy_po_pack'][$k1]['m3_sum'] = (string)($v1['qty']*$v1['ctn_m3']);
                        $data[$k]['buy_po_pack'][$k1]['note'] = getValue('buy_po_pack_remark',['po_pack_id'=>$v1['id']],'content');

                        if($v1['container_id'] > 0){
                            $data[$k]['is_container']=1;
                            $container = model('Buy')->getContainerStatus($v1['container_id'],$this->lang);
                            $data[$k]['buy_po_pack'][$k1]['name'] = $container['name'];
                            $data[$k]['buy_po_pack'][$k1]['container_status'] = $container['status'];
                            $data[$k]['buy_po_pack'][$k1]['container_time'] = $container['time'];
                        }else{
                            $data[$k]['is_container']=2;
                            $data[$k]['buy_po_pack'][$k1]['name'] = '';
                            $data[$k]['buy_po_pack'][$k1]['container_status'] = '';
                            $data[$k]['buy_po_pack'][$k1]['container_time'] = '';
                        }
                        
                    }
                }
                foreach ($data[$k]['buy_plan'] as $k2 => $v2) {
                    $data[$k]['buy_plan'][$k2]['kgs_sum'] = (string)$v2['kgs_sum'];
                    $data[$k]['buy_plan'][$k2]['m3_sum'] = (string)$v2['m3_sum'];
                }
            }
        }
        return $data;
    }

    // 采购合同
    public function list(Request $request)
    {   
        if($request->isAjax()){
            $join = [
                        ['company c','zu.company_id = c.id','LEFT'],
                        ['port p','zu.port_id = p.id','LEFT']        // 交货地址
                    ];
            $where['zu.status'] = 1;
            if(isset($this->data['play']) && $this->data['play'] == 'true') $where['zu.paid_sum'] = ['>',0];
            if(isset($this->data['sign']) && $this->data['sign'] == 'true') $where['zu.sign_day'] = ['>',0];
            if(isset($this->data['receipt']) && $this->data['receipt'] == 'true') $where['zu.receipt_day'] = ['>',0];
            if(isset($this->data['del']) && $this->data['del'] == 'true') $where['zu.status'] = 2;
            if(isset($this->data['searchText']) && $this->data['searchText']) $where['c.name'] = ['like','%'.$this->data['searchText'].'%'];

            if(session('admin')['position_id'] == 60){
                $where['zu.create_at'] = ['>',time()-3*365*24*60*60];
                $where['zu.create_id'] = ['in',getChildAdmin()];
            }else if(session('admin')['position_id'] == 63){
                $where['zu.create_at'] = ['>',time()-365*24*60*60];
                $where['zu.create_id'] = $this->user_id;
            }

            $data = model('Buy')->getBuyPo($where,$this->lang,'','');
            $data = $this->getReturnData($data);
            // dump($data);die;
            $returnData['size'] = count( $data);

            // 获取分页数据
            if(isset($this->data['page']) && isset($this->data['limit'])){
                if($this->data['limit']*($this->data['page']-1) < $returnData['size']){
                    $data = array_slice($data,$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                    $returnData['page'] = $this->data['page'];
                }
            }else{
                $returnData['page'] =1;
            }
            $returnData['data'] = $data;
            // dump($returnData);die;
            return json_encode(array('status'=>1,'data'=>$returnData));

            // return json_encode($data);
        }else{
            return view('list');
        }
        
    }

    // 生成采购合同
    public function addBuyPo()
    {
        Db::startTrans();
        // try{
            // $this->getOrganizPoData($this->data);
            if(empty($this->data['paypoarr'])) return json_encode(array('status'=>2,'msg'=>lang("payment_arrangement_can't_be_empty")));
            if(empty($this->data['ids'])) return json_encode(array('status'=>2,'msg'=>lang("planned_order_can't_be_empty")));
            if(empty($this->data['terms'])) return json_encode(array('status'=>2,'msg'=>lang("contract_terms_can't_be_empty")));

            $noticeText = noticeText($this->data['data'],['port_id'=>lang('delivery_address'),'company_id'=>lang('designated_company'),'linkman_id'=>lang('contact'),'bank_id'=>lang('bank_account'),'delivery_day'=>lang('delivery_time')]);
            if(!empty($noticeText)) return json_encode($noticeText);    

            unset($this->data['data']['country_id']);
            unset($this->data['data']['has_sum']);
            if(isset($this->data['data']['replace_sum'])){
                $this->data['data']['cost_sum'] = $this->data['data']['replace_sum'];
                unset($this->data['data']['replace_sum']);
            }
            $this->data['data']['delivery_day'] = strtotime($this->data['data']['delivery_day']);

            // $this->data['data']['cost_sum'] = $cost_sum;
            $this->data['data']['create_id'] = $this->user_id;
            $this->data['data']['create_at'] = time();
            $this->data['data']['update_id'] = $this->user_id;
            $this->data['data']['update_at'] = time();
            $this->data['data']['status'] = 1;
            $po_id = insertData('buy_po',$this->data['data']);
            if(!$po_id) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));
            // 给采购计划订单绑定采购合同ID
            foreach ($this->data['ids'] as $k => $v) {
                $res = updateData('buy_plan',['id'=>$v],['po_id'=>$po_id]);
            }
            if(!$res) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));


            // 添加当前合同的其他费用,并获取其他费用合计
            if (isset($this->data['cost_list']) && !empty($this->data['cost_list'])) {
                $cost_sum = $this->insertPoCost($po_id,$this->data['cost_list']);
            }else{
                $cost_sum = 0;
            }

            // 添加合同关联的条款信息
            foreach ($this->data['terms'] as $k1 => $v1) {
                if($v1['content']) 
                    $res1 = insertData('buy_po_terms',['po_id'=>$po_id,'type'=>$k1,'content'=>$v1['content']]);
            }
            if( isset($res1) && !$res1) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));

            // 添加付款安排（付款百分比，和各个百分比时间）
            foreach ($this->data['paypoarr'] as $k2 => $v2) {
                $v2['po_id'] = $po_id;
                $v2['pay_day'] = strtotime($v2['pay_day']);
                $res2 = insertData('buy_po_pay',$v2);       
            }
            if(!$res2) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));



            // 添加公司财务信息
            $fin_co_insert = [
                                'happen_day'=>$this->data['data']['delivery_day'],
                                'co_id'=>$this->data['data']['company_id'],
                                'type'=>1,
                                'amount'=>$this->data['data']['price_sum'] + $this->data['data']['paid_sum'],
                                'table_name'=>'buy_po',
                                'record_id'=>$po_id,
                                'create_id'=>$this->user_id,
                                'create_at'=>time(),
                            ];
            $res3 = insertData('fin_co',$fin_co_insert);

            if($po_id && $res){
                // 生成默认装箱单
                $createpack = $this->createPoPack($this->data['ids'],$po_id,$this->data['data']['port_id']);
                if($createpack == 1){
                    Db::commit();
                    return json_encode(array('status'=>1,'msg'=>lang('purchase_contract_addition_successfully')));
                }else{
                    Db::rollback();
                    return json_encode(array('status'=>2,'msg'=>'装箱单生成失败'));
                }
            }else{
                Db::rollback();
                return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));
            }
        // }catch(\Exception $e){
        //     Db::rollback();
        //     return json_encode(array('status'=>500,'msg'=>lang('系统报错mysql')));
        // }
    }

    function createPoPack($plan_ids,$po_id,$port_id,$createType='create')
    {
        // dump($plan_ids);die;
        foreach ($plan_ids as $k => $v) {
            // $pack_content[$k] = getDatas('buy_plan',['pro_id,prochar_id,ctn_qty num,ctn_kgs witch,ctn_m3 volume,ctn_size size,qty boxnum'],['id'=>$v])[0];
            $pack_content[$k] = DB::name('buy_plan')->field(['pro_id,prochar_id,ctn_qty num,ctn_kgs witch,ctn_m3 volume,ctn_size size,qty boxnum'])->where(['id'=>$v])->find();
            $pack_content[$k]['po_id'] = $po_id;
            $pack_content[$k]['port_id'] = $port_id;
        }
        $res = model('Buy')->buyPoPack($pack_content,$po_id,$createType);
        return $res['status'];
    }

    function getOrganizPoData($data)
    {

        $noticeText = noticeText($this->data['data'],['bank_id'=>lang('bank_account'),'company_id'=>lang('designated_company'),'delivery_day'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'linkman_id'=>lang('contact')]);
        if(!empty($noticeText)) return json_encode($noticeText);
        unset($this->data['data']['country_id']);
        unset($this->data['data']['has_sum']);
        if(isset($this->data['data']['replace_sum'])){
            $this->data['data']['cost_sum'] = $this->data['data']['replace_sum'];
            unset($this->data['data']['replace_sum']);
        }
        $this->data['data']['delivery_day'] = strtotime($this->data['data']['delivery_day']);
    }

    function insertPoCost($po_id,$cost_lst)
    {
        // dump($cost_lst);die;
        // 编辑合同其他费用
        $cost_sum = 0;
        foreach ($cost_lst as $k => $v) {
            $insertData['amount'] = $v['amount'];
            $insertData['apportion'] = isset($v['apportion']) && $v['apportion'] == 'true' ? 1 :0;
            $insertData['is_replace_pay'] = $v['is_replace_pay'] == 'true' ? 1 :0;
            $insertData['remarks'] = $v['remarks'];
            $insertData['po_id'] = $po_id;
            $res = insertData('buy_po_cost',$insertData);
            if(!$res) return json_encode(array('status'=>0,'msg'=>lang('failed_to_add_other_purchase_contract_expenses')));
            // 代付前提下，计算合同代付合计
            if($insertData['is_replace_pay'] == 1) $cost_sum += $v['amount'];
        }
        return $cost_sum;
        
    }

    public function editBuyPo(Request $request)
    {   
        if(isset($this->data['request']) && $this->data['request'] == 'update'){

            if(!isset($this->data['po_id'])) return json_encode(array('status'=>2,'msg'=>lang("please_select_a_contract")));
            if(empty($this->data['paypoarr'])) return json_encode(array('status'=>2,'msg'=>lang("payment_arrangement_can't_be_empty")));
            if(empty($this->data['ids'])) return json_encode(array('status'=>2,'msg'=>lang("planned_order_can't_be_empty")));
            if(empty($this->data['terms'])) return json_encode(array('status'=>2,'msg'=>lang("contract_terms_can't_be_empty")));

            $noticeText = noticeText($this->data['data'],['bank_id'=>lang('bank_account'),'company_id'=>lang('designated_company'),'delivery_day'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'linkman_id'=>lang('contact')]);
            if(!empty($noticeText)) return json_encode($noticeText);

            unset($this->data['data']['country_id']);
            unset($this->data['data']['has_sum']);
            if(isset($this->data['data']['replace_sum'])){
                $this->data['data']['cost_sum'] = $this->data['data']['replace_sum'];
                unset($this->data['data']['replace_sum']);
            }
            $this->data['data']['delivery_day'] = strtotime($this->data['data']['delivery_day']);

            // 获取被修改的字段信息 操作纪录
            $updateInfo = model('Buy')->getupdatelogs($this->data);
            if($updateInfo){
                $buy_po_logs['happen_at'] = time();
                $buy_po_logs['po_id'] = $this->data['po_id'];
                $buy_po_logs['admin_id'] = $this->user_id;
                $buy_po_logs['content'] = $updateInfo;
                $buy_po_logs_insert = insertData('buy_po_logs',$buy_po_logs);
            }

            // $this->getOrganizPoData($this->data);

            // return $this->data;
            // 编辑合同其他费用，先删除之前有的，再新增
            if (isset($this->data['cost_list']) && !empty($this->data['cost_list'])) {
                $resDel = deleteData('buy_po_cost',['po_id'=>$this->data['po_id']]);
                $this->insertPoCost($this->data['po_id'],$this->data['cost_list']);
            }

            $res = updateData('buy_po',['id'=>$this->data['po_id']],$this->data['data']);
            if($res < 0) return json_encode(array('status'=>0,'msg'=>lang('edit_failed'))); 

            // 编辑合同的计划订单
            $res4 = updateData('buy_plan',['po_id'=>$this->data['po_id']],['po_id'=>0]);
            foreach ($this->data['ids'] as $k3 => $v3) {
                $res5 = updateData('buy_plan',['id'=>$v3],['po_id'=>$this->data['po_id']]);

            }

            // 删除当前po_id下的付款安排，然后新增付款安排
            $res1 = deleteData('buy_po_pay',['po_id'=>$this->data['po_id']]);
            // if(!$res1) return json_encode(array('status'=>500,'msg'=>lang('edit_failed'))); 
            // 添加付款安排（付款百分比，和各个百分比时间）
            foreach ($this->data['paypoarr'] as $k2 => $v2) {
                $v2['po_id'] = $this->data['po_id'];
                $v2['pay_day'] = strtotime($v2['pay_day']);
                $res2 = insertData('buy_po_pay',$v2);       
            }
            if(!$res2) return json_encode(array('status'=>0,'msg'=>lang('edit_failed')));

            // 编辑合同条款
            foreach ($this->data['terms'] as $k1 => $v1) {
                if($v1['content']){
                    if(hasData('buy_po_terms',['po_id'=>$this->data['po_id'],'type'=>$k1])){
                        $res3 = updateData('buy_po_terms',['po_id'=>$this->data['po_id'],'type'=>$k1],['content'=>$v1['content']]);
                    }else{
                        $res3 = insertData('buy_po_terms',['po_id'=>$this->data['po_id'],'type'=>$k1,'content'=>$v1['content']]);
                    }    
                }
            }
            // if($res3<0) return json_encode(array('status'=>0,'msg'=>lang('edit_failed')));

            // 编辑装箱单信息
            if(isset($this->data['packing']) && !empty($this->data['packing'])){
                $res4 = model('Buy')->buyPoPack($this->data['packing'],$this->data['po_id'],'create');
                if($res4['status'] != 1) return  json_encode($res4);
                $this->data['ids'];
                // dump($this->data);die;
                // 判断是否存在采购计划未编辑装箱清单
                $plan_ids = [];
                foreach ($this->data['ids'] as $k4 => $v4) {
                    $plan = getDatas('buy_plan',['pro_id,prochar_id'],['id'=>$v4])[0];
                    if(!hasData('buy_po_pack',['po_id'=>$this->data['po_id'],'pro_id'=>$plan['pro_id'],'prochar_id'=>$plan['prochar_id']])){
                        $plan_ids[] = $v4; 
                    }
                }
                if($plan_ids) $res4 = $this->createPoPack($plan_ids,$this->data['po_id'],$this->data['data']['port_id'],'append');
                
            }

            // 编辑同一公司采购合同信息
            $fin_co_insert = [
                                'happen_day'=>$this->data['data']['delivery_day'],
                                'co_id'=>$this->data['data']['company_id'],
                                'amount'=>$this->data['data']['price_sum'] + $this->data['data']['paid_sum'],
                                'update_id'=>$this->user_id,
                                'update_at'=>time(),
                            ];
            $res3 = updateData('fin_co',['record_id'=>$this->data['po_id']],$fin_co_insert);

            return json_encode(array('status'=>1,'msg'=>lang('edited_successfully')));
        }else{
            // 根据合同ID  获取其计划订单（合同组成的订单）
            $plan_ids = getDatas('buy_plan',['id'],['po_id'=>$this->data['id']],'id desc');
            if(!empty($plan_ids)){
                foreach ($plan_ids as $k => $v) {
                    $ids[] = $v['id'];
                }
                $idstr = implode(',', $ids);
            }else{
                $idstr = '';
            }
            return view('buy/plan2po',['plan_ids'=>$idstr,'po_id'=>$this->data['id'],'title'=>lang("edit_purchase_contract"),'request'=>'edit']);
        } 

    }

    public function submitEditPlan()
    {
        if($this->data['request'] == 'add'){

        }
    }



    
    // 查看
    function checkView()
    {
        if(isset($this->data['id']) && $this->data['id'] ){
            if($this->data['request'] == 'view'){
                return view('detail',['id'=>$this->data['id']]);
            }else{
                $data = model('Buy')->getBuyPo(['zu.id'=>$this->data['id']],$this->lang,'','');
                $data = $this->getReturnData($data);
                if(!empty($data)){
                    $data = $data[0];
                    $data['status_name'] = '准备中';
                    $data['status_name'] = $data['sign_day'] ? '已签约' : $data['status_name'];
                    $data['status_name'] = $data['receipt_day'] ? '已收货' : $data['status_name'];
                    $data['status_name'] = $data['finish_day'] ? '已完成' : $data['status_name'];
                }
                // dump($data);;die;
                return json_encode($data);
            }
        }else{
            return "黑脸问号？？？？？？？？";
        }
    }

    // 获取合同条款
    function getPoTerms()
    {
        return json_encode($this->getPoTerms_($this->data['id']));
    }
    // 获取合同条款
    function getPoTerms_($po_id)
    {
        $terms = getDatas('buy_po_terms',['*'],['po_id'=>$po_id]);
        if(!empty($terms)){
            foreach ($terms as $k => $v) {
                // ，general_terms=常规条款 ,delivery_terms=送货条款 ,payment_terms=付款条款 ,after_sales_terms=售后条款
                switch ($v['type']) {
                    case 'general_terms':
                        $terms[$k]['terms_type_name'] = '常规条款';
                        break;
                    case 'delivery_terms':
                        $terms[$k]['terms_type_name'] = '送货条款';
                        break;
                    case 'payment_terms':
                        $terms[$k]['terms_type_name'] = '付款条款';
                        break;
                    case 'after_sales_terms':
                        $terms[$k]['terms_type_name'] = '售后条款';
                        break;
                }
                
            }
        }
        return $terms;
    }
    //获取支付信息
    function getPoFinance()
    {   

        $buyPo = Db::name('buy_po')->where(['id'=>$this->data['id']])->find();
        // 获取支付账号
        $bank = getSearch('co_bank','zu',['zu.id,zu.bankname,zu.account_name,zu.account_num,zu.is_main,b.name'],['zu.id'=>$buyPo['bank_id']],[['banks b','zu.banks_id = b.id']],'zu.id desc');


        // 支付内容
        $paycontent = getDatas('buy_po_cost',['*'],['po_id'=>$this->data['id']]);

        // 付款安排
        $payplan = getDatas('buy_po_pay',['*'],['po_id'=>$this->data['id']]);
        foreach ($payplan as $k => $v) {
            $payplan[$k]['pay_time'] = getTimeDates($v['pay_day'],$this->lang,true);
        }

        // 付款記錄
        $join = [
                    ['fin_co2buy f','zu.fin_co2buy_id = f.id'],
                    ['fin_co2buy_remarks r','f.id = r.fin_co2buy_id'],
                    ['accounts a','f.account_id = a.id'],
                    ['banks ab','a.banks_id = ab.id'],
                    ['co_bank c','f.bank_id = c.id'],
                    ['banks cb','c.banks_id = cb.id'],
                ];
        $field = ['zu.amount,f.happen_day,f.account_id,f.create_id,f.create_at,f.bank_id,r.remarks,a.bankname,a.account_name,a.account_num,ab.name bank_name,c.bankname bankname_,c.account_name account_name_,c.account_num account_num_,cb.name bank_name_'];
        $payRecord = getSearch('fin_co2buy_po','zu',$field,['zu.po_id'=>$this->data['id']],$join,'zu.id desc');
        foreach ($payRecord as $k1 => $v1) {
            $payRecord[$k1]['happen_time'] = getTimeDates($v1['happen_day'],$this->lang,true);
            $payRecord[$k1]['create_name'] = getValue('admin',['id'=>$v1['create_id']],'nickname');
            $payRecord[$k1]['create_time'] = getTimeDates($v1['create_at'],$this->lang,true);
        }
        // $payRecord = getDatas('fin_co2buy_po',['*'],['po_id'=>$this->data['id']]);
        // dump($payRecord);die;
        $returnData['bank'] = $bank[0];
        $returnData['payplan'] = $payplan;
        $returnData['payRecord'] = $payRecord;
        $returnData['paycontent'] = $paycontent;
        return json_encode($returnData);
    }

    function getLinkman($data)
    {
        $linkman = $data;
        $linkman['linkmethod'] = '';
        $linkman_method = getDatas('linkman_method',['coattr_id,content'],['linkman_id'=>$data['id'],'coattr_id'=>['in','1,2']]);
        $linkman['linkmethod'] = implode(array_column($linkman_method, 'content'),',');
        return $linkman;
    }

    function print()
    {
        // 合同信息
        $buyPo = Db::name('buy_po')->where(['id'=>$this->data['id']])->find();
        $buyPo['sellcompany_name'] = getValue('company',['id'=>$buyPo['company_id']],'name');
        $buyPo['sellcompany_addr'] = getValue('co_profile',['co_id'=>$buyPo['company_id']],'addr');

        // 合同指定公司联系人/联系方式
        $sellcompany_linkman = Db::name('linkman')->where(['id'=>$buyPo['linkman_id']])->find();
        $sellcompany_linkman = $this->getLinkman($sellcompany_linkman);

        // amdinInfo
        $amdinInfo = Db::name('admin')->where(['id'=>$buyPo['create_id']])->find();
        $linkman_method = getDatas('adminattr_value',['coattr_id,content'],['admin_id'=>$amdinInfo['id'],'coattr_id'=>['in','1,2']]);
        $amdinInfo['linkmethod'] = implode(array_column($linkman_method, 'content'),',');
        

        // 合同产品
        $buyPoPro = getDatas('buy_po_pack',['*'],['po_id'=>$buyPo['id']]);
        $buyPoProPriceSum = 0;
        if(!empty($buyPoPro)){
            foreach ($buyPoPro as $k1 => $v1) {
                $buyPoPro[$k1]['proInfo'] = getProAndProchar($v1,$this->lang);
                $buyPoPro[$k1]['proInfo']['prochar_id'] = numzero($buyPoPro[$k1]['proInfo']['prochar_id']);
                $buyPoPro[$k1]['proInfo']['brand_name'] = $buyPoPro[$k1]['proInfo']['brand_name'] ? ' / '.$buyPoPro[$k1]['proInfo']['brand_name'] : '';
                $buyPoPro[$k1]['proInfo']['model'] = $buyPoPro[$k1]['proInfo']['model'] ? ' / '.$buyPoPro[$k1]['proInfo']['model'] : '';
                $buyPoPro[$k1]['price'] = getValue('buy_plan',['po_id'=>$buyPo['id'],'pro_id'=>$v1['pro_id'],'prochar_id'=>$v1['prochar_id']],'price');
                $buyPoProPriceSum += $buyPoPro[$k1]['price']*$buyPoPro[$k1]['qty']*$buyPoPro[$k1]['ctn_qty'];

                // 获取产品角色特征
                $feature = Db::name('profeature2char')->where(['pro_id'=>$v1['pro_id'],'prochar_id'=>$v1['prochar_id']])->select();
                $buyPoPro[$k1]['feature'] = '';
                if(!empty($feature)){
                    foreach ($feature as $k_feature => $v_feature) {
                        $buyPoPro[$k1]['feature'] .= ' / '.getValue('multi_lang',['mkey'=>'proattr_'.$v_feature['profeature_id'],'lang'=>$this->lang],'content');
                        $buyPoPro[$k1]['feature'] .= ':'.getValue('multi_lang',['mkey'=>'proattr_value_'.$v_feature['profeature_value_id'],'lang'=>$this->lang],'content');
                    }    
                }
                
                // 产品角色的 介绍说明
                $prodesc = getDatas('prodesc',['prodesc_cat_id,content'],['pro_id'=>$v1['pro_id'],'prochar_id'=>$v1['prochar_id'],'lang'=>$this->lang]);
                foreach ($prodesc as $k1_ => $v1_) {
                    $prodesc[$k1_]['prodesc_cat_name'] = getValue('multi_lang',['mkey'=>'prodesc_cat_'.$v1_['prodesc_cat_id'],'lang'=>$this->lang],'content');
                }
                $buyPoPro[$k1]['prodesc_cat'] = $prodesc;
            }
        }

        // 其他费用
        $buyPoCost = getDatas('buy_po_cost',['*'],['po_id'=>$buyPo['id']]);
        $buyPoCostAmountSum = 0;
        if(!empty($buyPoCost)){
            foreach ($buyPoCost as $k2 => $v2) {
                $buyPoCostAmountSum += $v2['amount'];
            }
        }

        // 合同条款
        $terms = $this->getPoTerms_($buyPo['id']);
        foreach ($terms as $k3 => $v3) {
            // 追加送货条款 内容
            if($v3['type'] == 'delivery_terms'){
                $str = '以上产品于 '.getTimeDates($buyPo['delivery_day'],$this->lang,true).' 送到 '.getValue('port',['id'=>$buyPo['port_id']],'name')."。\r\n";
                $terms[$k3]['content'] = $str.$v3['content'];
            }
            // 付款条款根据付款安排 追加显示内容
            if($v3['type'] == 'payment_terms'){
                $buy_po_pay = getDatas('buy_po_pay',['*'],['po_id'=>$buyPo['id']],'id asc');
                $str = '';
                foreach ($buy_po_pay as $k3_ => $v3_) {
                   $str .= "合同货款于".getTimeDates($v3_['pay_day'],$this->lang,true)."支付金额 ".number_format($v3_['amount'],2)." 元(占总额的 ".$v3_['percent']." %)。\r\n";
                }
                $co_bank = Db::name('co_bank')->where(['id'=>$buyPo['bank_id']])->find();
                $bank_name = getValue('banks',['id'=>$co_bank['banks_id']],'name');
                $str .= "付款账号为：".$bank_name.' '.$co_bank['bankname']."，户名： ".$co_bank['account_name']." ， 账号：".$co_bank['account_num']." 。\r\n";
                $terms[$k3]['content'] = $str.$v3['content'];
            }
        }

        // dump($terms);die;
        return view('print',[
                                'po_id'=>numzero($this->data['id']),
                                'buyPo'=>$buyPo,
                                'admin_name'=>getValue('admin',['id'=>$this->user_id],'nickname'),
                                'time'=>getTimeDates(time(),$this->lang),
                                'sellcompany_linkman'=>$sellcompany_linkman,
                                'amdinInfo'=>$amdinInfo,
                                'buyPoPro'=>$buyPoPro,
                                'buyPoProPriceSum'=>number_format($buyPoProPriceSum,2),
                                'buyPoProPriceSum_'=>$buyPoProPriceSum,
                                'buyPoCost'=>$buyPoCost,
                                'buyPoCostAmountSum'=>number_format($buyPoCostAmountSum,2),
                                'buyPoCostAmountSum_'=>$buyPoCostAmountSum,
                                'terms'=>$terms,
                            ]);
        
    }

    // 批量签约
    public function batchSign()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("please_select_contract_to_confirm_signature")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'sign');
        return json_encode($res);
    }

    // 批量收货
    public function batchReceipt()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("select_contract_to_cofirm_receipt")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'receipt');
        return json_encode($res);
    }

    // 取消收货
    public function batchIsReceipt()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("select_contract_to_cofirm_receipt")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'isreceipt');
        return json_encode($res);
    }

    // 批量删除
    public function batchDel()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("select_contract_to_delete")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'del',$this->user_id);
        return json_encode($res);
    }


    // 取消签约
    public function batchCancelSign()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>'取消签约失败，请正确选择需要签约的数据'));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'CancelSign',$this->user_id);
        return json_encode($res);
        
    }


    function getpdf()
    {
        buypopdfphp();
    }

}